import random

from shop import conf
from shop.model import save_phone_code
from shop.util.mylogger import Alogger


def send_message(phone):
    # 短信应用 SDK AppID
    appid = int(conf.MESSAGE_APP_ID)  # SDK AppID 以1400开头
    # 短信应用 SDK AppKey
    appkey = conf.MESSAGE_APP_KEY
    # 需要发送短信的手机号码
    phone_numbers = [phone]
    # 短信模板ID，需要在短信控制台中申请
    template_id = conf.MESSAGE_TEMPLATE_ID  # NOTE: 这里的模板 ID`7839`只是示例，真实的模板 ID 需要在短信控制台中申请
    # 签名
    sms_sign = conf.MESSAGE_SMS_SIGN  # NOTE: 签名参数使用的是`签名内容`，而不是`签名ID`。这里的签名"腾讯云"只是示例，真实的签名需要在短信控制台中申请

    from qcloudsms_py import SmsSingleSender
    from qcloudsms_py.httpclient import HTTPError

    ssender = SmsSingleSender(appid, appkey)

    # 随机生成一个验证码，并存入redis中,并发送短信
    num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    code = ""
    for i in range(4):
        code = code + str(random.choice(num_list))
    save_phone_code(phone, code)
    params = [code]  # 当模板没有参数时，`params = []`

    try:
        result = ssender.send_with_param(86, phone_numbers[0],
                                         template_id, params, sign=sms_sign, extend="", ext="")
        Alogger.info(result)
    except HTTPError as e:
        print(e)
    except Exception as e:
        print(e)
